import {
  createRouter,
  createWebHashHistory,
  createWebHistory,
} from "vue-router";
import { staticRouter, errorRouter } from "@/routers/modules/staticRouter";
import nprogress from "@/utils/nprogress";
// .env配置文件读取
const mode = import.meta.env.VITE_ROUTER_MODE;

// 路由访问两种模式：带#号的哈希模式，正常路径的web模式。
const routerMode: any = {
  hash: () => createWebHashHistory(),
  history: () => createWebHistory(),
};

// 创建路由器对象
const router = createRouter({
  // 路由模式hash或者默认不带#
  history: routerMode[mode](),
  routes: [...staticRouter, ...errorRouter],
  strict: false,
  // 滚动行为
  scrollBehavior() {
    return {
      left: 0,
      top: 0,
    };
  },
});

/**
 * @description 前置路由
 * */
router.beforeEach(async (to: any, from: any, next: any) => {
  next();
});

/**
 * @description 重置路由
 */
// export const resetRouter = () => {
//   const authStore = useAuthStore();
//   authStore.getMenuList.forEach((route: any) => {
//     const { name } = route;
//     if (name && router.hasRoute(name)) {
//       router.removeRoute(name);
//     }
//   });
// };

/**
 * @description 路由跳转错误
 */
router.onError((error) => {
  // 结束全屏动画
  nprogress.done();
  console.warn("路由错误", error.message);
});

/**
 * @description 后置路由
 */
// @ts-ignore
router.afterEach((to: any, from: any) => {
  // console.log("后置守卫", to, from);
  // 结束全屏动画
  nprogress.done();
});

export default router;
